iT邦幫忙

2022 iThome 鐵人賽

DAY 10
0

You're an avid bird watcher that keeps track of how many birds have visited your garden on any given day.

You decided to bring your bird watching to a new level and implement a few tools that will help you track and process the data.

You have chosen to store the data as a list of integers. The first number in the list is the number of birds that visited your garden today, the second yesterday, and so on.

1. Check how many birds visited today

Implement the BirdCount.today/1 function. It should take a list of daily bird counts and return today's count. If the list is empty, it should return nil.

2. Increment today's count

Implement the BirdCount.increment_day_count/1 function. It should take a list of daily bird counts and increment the today's count by 1. If the list is empty, return [1].

3. Check if there was a day with no visiting birds

Implement the BirdCount.has_day_without_birds?/1 function. It should take a list of daily bird counts. It should return true if there was at least one day when no birds visited the garden, and false otherwise.

4. Calculate the total number of visiting birds

Implement the BirdCount.total/1 function. It should take a list of daily bird counts and return the total number that visited your garden since you started collecting the data.

5. Calculate the number of busy days

Some days are busier than others. A busy day is one where five or more birds have visited your garden.

Implement the BirdCount.busy_days/1 function. It should take a list of daily bird counts and return the number of busy days.


https://exercism.org/tracks/elixir/exercises/bird-count

defmodule BirdCount do
  def today([]), do: nil

  def today(list) do
    hd list
  end

  def increment_day_count([]), do: [1]

  def increment_day_count(list) do
    result = list
    |> today
    |> Kernel.+(1)

    [result | tl list]
  end

  def has_day_without_birds?([]), do: false

  def has_day_without_birds?([head | tail]) do
    case head do
      0 -> true
      _ -> has_day_without_birds? tail
    end
  end

  def total([]), do: 0

  def total([head | tail]) do
    head + total tail
  end

  def busy_days([]), do: 0

  def busy_days([head | tail]) do
    if head >= 5, do: 1 + busy_days(tail), else: busy_days(tail)

    # if head >= 5 do
    #   1 + busy_days tail
    # else
    #   busy_days tail
    # end

    # cond do
    #   head >= 5 -> 1 + busy_days tail
    #   head < 5 -> busy_days tail
    # end
  end
end

上一篇
九.Tuples
下一篇
十一. Maps
系列文
戀戀 Elixir30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言